package com.whalecloud.chart.service.draw;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whalecloud.chart.domain.DrawChartRequestDTO;
import com.whalecloud.chart.service.AbstractChartService;
import com.whalecloud.chart.service.dto.LineValue;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

import java.util.List;

/**
 * @Description 折线图
 * @Author MarkAsh
 * @Date 2025/2/22
 **/
public class LineChartService extends AbstractChartService {

    public static void main(String[] args) {
        // 创建数据


    }

    /**
     * 创建数据集
     *
     * @param sourceData 源数据
     * @return 数据集
     */
    @Override
    public DefaultCategoryDataset createDataset(JSONArray sourceData) {
        DrawChartRequestDTO requestDTO = getRequestDTO();
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        sourceData.forEach(item -> {
            LineValue barValue = JSONObject.parseObject(JSONObject.toJSONString(item), LineValue.class);
            String value = barValue.getValue();
            double v = NumberUtil.isNumber(value) ? Double.parseDouble(value) : 0d;
            dataset.addValue(v, StrUtil.blankToDefault(requestDTO.getXLabel(), "X"), barValue.getCategory());
        });
        return dataset;
    }

    /**
     * 绘制图表
     *
     * @param dataset 数据集
     * @return 图表
     */
    @Override
    public JFreeChart createChart(DefaultCategoryDataset dataset) {
        DrawChartRequestDTO requestDTO = getRequestDTO();
        return ChartFactory.createLineChart(
                StrUtil.blankToDefault(requestDTO.getTitle(), "Example"), // 图标标题
                StrUtil.blankToDefault(requestDTO.getXLabel(), "X轴"), // X轴标签
                StrUtil.blankToDefault(requestDTO.getYLabel(), "Y轴"), // Y轴标签
                dataset,
                PlotOrientation.VERTICAL,
                true,
                true,
                false
        );
    }

    /**
     * 获取示例数据
     *
     * @return 示例数据
     */
    @Override
    public JSONArray getSampleData() {
        List<LineValue> barValues = List.of(
                new LineValue("A", "10"),
                new LineValue("B", "20"),
                new LineValue("C", "30"),
                new LineValue("D", "40"),
                new LineValue("E", "50")
        );
        return JSONArray.parseArray(JSONObject.toJSONString(barValues));
    }
}

